<?php
require_once('HttpInputFilter.class.php');
require_once('Validator.class.php');
require_once('HandlerBase.class.php');

class AjaxService {
	private static $moduleMap = array(
									'user' => 'UserHandler'
								);
	public static function dispatchRequest() {
		$f = new HttpInputFilter($_REQUEST);
		$op = $f->getNoneEmpty('op');
		$mod = $f->getNoneEmpty('mod');
		$assert = HttpInputFilter::assertNotNull($op, $mod);
		if (!$assert) {
			self::writeInvalidResponse();
		}
		
		if (!array_key_exists($mod, self::$moduleMap)) {
			self::writeInvalidResponse();
		}
		
		$classname = self::$moduleMap[$mod];
		$file = dirname(__FILE__)."/$classname.class.php";
		if (file_exists($file)) {
			require_once($file);
		} else {
			self::writeInvalidResponse();
		}
		$handler =  new $classname($_REQUEST);
		if (!$handler) {
			self::writeInvalidResponse();
		}
		ob_start(array(__CLASS__, 'obCallback'));
		$handler->doHandle($op);
	}
	private static function writeInvalidResponse()
	{
		self::setHeaders();
		die('{re:false, msg:"invalid request"}');
	}
	public static function setHeaders()
	{
		header('Content-Type:text/x-json;charset=UTF-8');
		header('Pragma: no-cache');
		header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
		header('Expires: Sat, 11 Aug 1984 00:00:00 GMT'); 
	}
	
	/**
	 * Comments out any output content for JavaScript eval()
	 *
	 * @param string $buff
	 * @return return
	 */
	public static function obCallback($buff)
	{
		if (strlen($buff) == 0) return '';
		else
		return '//'.str_replace("\n", "\n//", str_replace("\r", '', $buff))."\n";
	}
}
?>